package com.example.app15_handler.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.app15_handler.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class AsyncTaskActivity extends AppCompatActivity {

    private static final String TAG = "AsyncTaskActivity";

    private File apkFile;

    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_async_task);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        Log.i(TAG, "onCreate()");
    }

    /**
     * 下载apk
     * @param view v
     */
    public void downloadApk(View view) {
        // 启动异步任务
        new AsyncTask<Void, Integer, Void>() {

            // 主线程显示提示视图
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = new ProgressDialog(AsyncTaskActivity.this);
                dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                dialog.show();
                // 准备用于保存apk文件的File对象
                apkFile = new File(getExternalFilesDir(null), "update.apk");
            }

            // 分线程，联网请求数据
            @Override
            protected Void doInBackground(Void... voids) {
                String path = "http://10.189.124.52:8080/apk/app12_data_storage-debug.apk";

                try {
                    // 获取连接对象
                    URL url = new URL(path);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    // 设置超时时间
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(10000);
                    // 连接
                    connection.connect();
                    if (connection.getResponseCode() == 200) {
                        // 设置进度条的最大值
                        dialog.setMax(connection.getContentLength());

                        // 获取apk文件的InputStream
                        InputStream in = connection.getInputStream();
                        // 获取指向apkFile的OutputStream
                        OutputStream out = new FileOutputStream(apkFile);
                        byte[] buf = new byte[1024];
                        int len;
                        while((len = in.read(buf)) != -1) {
                            out.write(buf, 0, len);
                            // 显示下载进度
                            // dialog.incrementProgressBy(len);
                            publishProgress(len);
                            // 模拟网络
                            // Thread.sleep(50);
                            SystemClock.sleep(50);
                        }

                        out.close();
                        in.close();
                    }

                    // 下载完成，关闭连接
                    connection.disconnect();

                } catch (IOException e) {
                    dialog.dismiss();
                    Log.e(TAG, "onClick: " + e.getMessage(), e);
                    Thread.currentThread().interrupt();
                }
                return null;
            }

            // 主线程，更新界面
            @Override
            protected void onPostExecute(Void unused) {
                super.onPostExecute(unused);
                dialog.dismiss();
                installApk();
            }

            // 在主线程中更新进度
            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                dialog.incrementProgressBy(values[0]);
            }
        }.execute();
    }

    /**
     * 启动安装apk
     */
    private void installApk() {
        Intent installIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        installIntent.setDataAndType(Uri.fromFile(apkFile),
                "application/vnd.android.package-archive");
        startActivity(installIntent);
    }

}